<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分销商id" prop="franchiserId">
        <el-input
          v-model="queryParams.franchiserId"
          placeholder="请输入分销商id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上线id" prop="primaryId">
        <el-input
          v-model="queryParams.primaryId"
          placeholder="请输入上线id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置搜索条件</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="handleFetechAllFranchiser">全量获取分销商库</el-button>
        <el-button icon="el-icon-delete" size="mini" @click="handleDeleteAllFranchiser">清空分销商数据</el-button>
      </el-form-item>
      <el-form-item :label="taskDesc" prop="remark">
          <!-- <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" /> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="franchiserList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="分销商id" align="center" prop="franchiserId" />
      <el-table-column label="昵称" align="center" prop="name" />
      <!-- <el-table-column label="Sliver" align="center" prop="0" /> -->
      <el-table-column label="等级" align="center" prop="level" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="是否主号" align="center">
        <template slot-scope="scope">
          <span>{{ primaryState(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属主号" align="center">
      <template slot-scope="scope">
          <span>{{ primaryIdState(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上线分销商id" align="center">
        <template slot-scope="scope">
          <span>{{ agentUplineState(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button 
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >更新</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleModifyPassword(scope.row)"
          >修改密码</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >禁用</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 更新页面 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="昵称" prop="name">
              <el-input v-model="form.name" placeholder="请输入昵称" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24" width="20px">
            <el-form-item label="等级" prop="level">
              <el-input v-model="form.level" placeholder="请输入等级" disabled />
            </el-form-item>
          </el-col>

          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" disabled />
          </el-form-item>
          <el-col :span="24" v-if="formPrimarySelect">
            <el-form-item label="是否副号" prop="primaryOrNot1">
              <el-select v-model="formPrimaryOrNot1" placeholder="选择" @change="handleSelectPrimary">
                <el-option
                  v-for="dict in dict.type.franchiser_primary_or_not"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="formPrimaryId" label="主号id" prop="primaryId">
          <el-input v-model="form.primaryId" placeholder="请输入主号id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog :title="title" :visible.sync="modifyPasswordOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="昵称" prop="name">
              <el-input v-model="form.name" placeholder="请输入昵称" disabled/>
            </el-form-item>
          </el-col>
          <el-form-item label="密码" prop="phone">
            <el-input v-model="form.password" placeholder="请输入新密码"/>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPassword">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="tipsTitle" :visible.sync="tipsOpen" width="500px" append-to-body>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormOk">确 定</el-button>
        <el-button @click="cancelOk">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFranchiser, getFranchiser, delFranchiser, addFranchiser, updateFranchiser, updateFranchiserPassword, fetchAllFranchiser, deleteAllFranchiser, fetchAllFranchiserTask} from "@/api/system/franchiser";

export default {
  name: "Franchiser",
  dicts: ['franchiser_primary_or_not'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      franchiserList: [],
      // 弹出层标题
      title: "",
      taskDesc: "",
      // 是否显示弹出层
      open: false,
      modifyPasswordOpen: false,
      formPrimaryOrNot1: "0",     // 是否设置副号的select
      formPrimaryId: false,
      formPrimarySelect: false,
      fetchAllFranchiserTaskRuning: false,
      fetchFranchiserInterval: null,
      tipsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        franchiserId: null,
        name: null,
        level: null,
        phone: null,
        primaryId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        franchiserId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        // name: [
        //   { required: true, message: "$comment不能为空", trigger: "blur" }
        // ],
        level: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        // phone: [
        //   { required: true, message: "$comment不能为空", trigger: "blur" }
        // ],
        primaryOrNot: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        primaryId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();

    fetchAllFranchiserTask().then(response => {
      if (response && response.msg == "0") {
        if (this.fetchFranchiserInterval) {
          clearInterval(this.fetchFranchiserInterval)
          this.fetchFranchiserInterval = null;
          this.taskDesc = "获取完成";
        } else {
          this.taskDesc = "";
        }
      } else if (response && response.msg == "1") {
        this.addFetchTaskInterval();
      }
    });
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listFranchiser(this.queryParams).then(response => {
        this.franchiserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    primaryState(row) {
      if (row.level != 2) {
        return "无状态"
      }
      if (row.primaryId > 0) {
        return "副号";
      }
      return "主号"
    },

    agentUplineState(row) {
      if (row.level != 4) {
        return "-"
      }
      return row.agentUpline;
    },

    primaryIdState(row) {
      if (row.primaryId > 0) {
        return row.primaryId;
      }
      return "-"
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.modifyPasswordOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        franchiserId: null,
        name: null,
        level: null,
        phone: null,
        primaryOrNot: null,
        primaryId: null,
        password: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加【请填写功能名称】";
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFranchiser(id).then(response => {
        this.form = response.data;

        this.oldPrimaryId = this.form.primaryId;

        this.formPrimaryOrNot1 = this.form.primaryId > 0 ? "1" : "0";
        this.formPrimarySelect = this.form.level == 2
        this.formPrimaryId = (this.formPrimarySelect && this.formPrimaryOrNot1 == "1")
        this.open = true;
        this.title = "修改分销商信息";
      });
    },

    handleModifyPassword(row) {
      this.reset();
      const id = row.id || this.ids
      getFranchiser(id).then(response => {
        this.form = response.data;
        this.modifyPasswordOpen = true;
        this.title = "修改密码";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.oldPrimaryId != this.form.primaryId && (this.oldPrimaryId == 0 || this.form.primaryId == 0)) {
              if (this.oldPrimaryId == 0) {
                this.tipsTitle = `是否要更改为${this.form.primaryId}的副号？同时该主号下的其他副号将一并转移`;
                this.tipsOpen = true;
              } else {
                this.tipsTitle = `该账号为${this.oldPrimaryId}名下副号,修改后${this.oldPrimaryId}将变成副号，是否修改？`;
                this.tipsOpen = true;
              }
              return;
            }

            updateFranchiser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFranchiser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitFormOk() {
      updateFranchiser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.tipsOpen = false;
              this.getList();
            });
    },

    cancelOk() {
      this.tipsOpen = false;
    },

    submitPassword() {
      if (!this.form.password || this.form.password.length < 8) {
        this.$modal.msgSuccess("密码需要至少8个字符");
        return;
      }
      console.log(this.form)
      updateFranchiserPassword({id: this.form.id, password: this.form.password}).then(response => {
        this.$modal.msgSuccess("密码修改成功");
        this.modifyPasswordOpen = false;
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delFranchiser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleSelectPrimary(sel) {
      // console.log(sel)
      this.form.primaryOrNot = sel == "1" ? "0":"1";
      this.formPrimaryId = sel == "1"
      if (sel == "0") {
        this.form.primaryId = 0
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/franchiser/export', {
        ...this.queryParams
      }, `franchiser_${new Date().getTime()}.xlsx`)
    },

    addFetchTaskInterval() {
      this.taskDesc = this.taskDesc + "."
      fetchAllFranchiserTask().then(response => {
        if (response == "0") {
          clearInterval(this.fetchFranchiserInterval)
          this.fetchFranchiserInterval = null;
          this.taskDesc = "获取完成";
          this.getList();
        }
      });
    },

    handleFetechAllFranchiser() {
      // fetchAllFranchiserTaskRuning: false,
      // fetchFranchiserInterval: null,
      if (this.fetchFranchiserInterval) {
        clearInterval(this.fetchFranchiserInterval)
        this.fetchFranchiserInterval = null;
      }

      fetchAllFranchiser({}).then(response => {
        // console.log(response);
        this.$modal.msgSuccess("开始执行任务");
        this.taskDesc = "获取中"
        this.fetchFranchiserInterval = setInterval(() => {
          this.addFetchTaskInterval();
        }, 2000);
      })
    },

    handleDeleteAllFranchiser() {
      deleteAllFranchiser().then(response => {
        this.$modal.msgSuccess("清空成功");
        this.getList();
      });
    },

        // 设置选中的值
    setSelectValue(selectId, valueToSet) {
      var selectElement = document.getElementById(selectId);
      for (var i = 0; i < selectElement.options.length; i++) {
        if (selectElement.options[i].value === valueToSet) {
          selectElement.options[i].selected = true;
          break;
        }
      }
    }
  }
};
</script>
